let dropdown;
let form;
let tree;
let treeMenuTab;
let treeData = [];
let pAllData = []
let parentIdStrs = '0';
layui.use(['treeTable', 'layer', 'code', 'form', 'tree', 'dropdown', 'jquery',], function () {
    let o = layui.$
        , layer = layui.layer
        , util = layui.util
        , treeTable = layui.treeTable;
    tree = layui.tree;
    form = layui.form;
    dropdown = layui.dropdown;

    let auth_token = localStorage.getItem('auth_token');
    let headers = {
        // Basic bearer
        'Authorization': auth_token
        //'Authorization':'Basic '+auth_token
    }

    let params = {
        'pName': ''
    }
    //获取菜单数据
    $.DPost("/p/v1/queryPermissionTreeList", params, headers, function (data) {
        // 所以权限菜单数据；未递归排序
        pAllData = data.data.allData;
        pAllData.push({
            title: '系统权限根节点'
            , href: "/"
            , id: 0
            , spread: true
            , checked: false
        })
        //数据说明：id对应id，title对应menuName，href对应menuPath
        for (let p of data.data.treeData) {
            let tree = {
                field: p.title
                , title: p.title
                , id: p.id
                , pId: p.pId
                // , href: p.pUrl
                , spread: true // 节点是否初始展开
                , checked: false
                , children: p.children
                , child: p.children
            };
            treeData.push(tree);
        }
        //开启节点操作图标
        treeMenuTab = tree.render({
            elem: '#permissionTree'
            , id: 'permissionTree'
            , data: [{
                title: '系统权限根节点'
                , href: "/"
                , id: 0
                , spread: true
                , checked: false
                , children: treeData
            }]
            , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
            , showCheckbox: true  //是否显示复选框
            , edit: ['add', 'update', 'del'] //操作节点的图标
            , click: function (obj) {
                // 点击事件
                console.log(obj.data); //得到当前点击的节点数据
                console.log(obj.state); //得到当前节点的展开状态：open、close、normal
                console.log(obj.elem); //得到当前节点元素
                console.log(obj.data.children); //当前节点下是否有子节点
            }, operate: function (obj) {
                var type = obj.type; //得到操作类型：add、edit、del
                var data = obj.data; //得到当前节点的数据

                if (type === 'add') { //增加节点
                    permissionEditSub(headers, 'add', undefined)
                } else if (type === 'update') { //修改节点
                    permissionEditSub(headers, 'edit', data)
                } else if (type === 'del') { //删除节点
                    layer.confirm('确认删除吗？', function (index) {
                        // 向服务端发送删除指令
                        $.delete("/p/v1/delete?pId=" + data.id, {}, headers, function (data) {
                            if (data.code === '00000') {
                                layer.msg('删除成功', {icon: 6});
                            } else {
                                layer.msg(data.msg, {icon: 6});
                            }
                            // 表格刷新
                            treeMenuTab.reload();
                            layer.close(index);
                        })
                    });
                }
                ;
            }
        });
    });
});

/**
 * 权限菜单编辑
 * @param headers
 * @param type
 * @param userData
 */
function permissionEditSub(headers, type, permissData) {
    // 重置表单
    $("#permissionForm")[0].reset();
    layer.open({
        type: '1',
        content: $('.permissionEditDiv'),
        title: '编辑',
        area: ['850px', '500px'],
        btn: ['保存', '取消'],
        closeBtn: '1',
        success: function (layero, index) {
            let downTreeData = treeData;
            // 初始化查询权限数据
            let pData;
            if (type === 'edit') {
                $.DGet("/p/v1/queryPermissionOne?pId=" + permissData.id, {}, headers, function (data) {
                    if (data.code === '00000') {
                        pData = data.data
                        // 回显操作表单
                        // 权限类型
                        if (pData.pType == 'menu') {
                            $("input[name='pType'][value='menu']").attr("checked", true);
                        } else if (pData.pType == 'button') {
                            $("input[name='pType'][value='button']").attr("checked", true);
                        }
                        // 是否可用
                        if (pData.pAvailable == 0) {
                            $("input[name='pAvailable'][value='0']").attr("checked", true);
                        } else if (pData.pAvailable == 1) {
                            $("input[name='pAvailable'][value='1']").attr("checked", true);
                        }
                        // 请求类型
                        if (pData.pReqType == 'GET') {
                            $("input[name='pReqType'][value='GET']").attr("checked", true);
                        } else if (pData.pReqType == 'POST') {
                            $("input[name='pReqType'][value='POST']").attr("checked", true);
                        } else if (pData.pReqType == 'DELETE') {
                            $("input[name='pReqType'][value='DELETE']").attr("checked", true);
                        }
                        $("#permissionForm").form(pData);
                        form.render();
                        // 渲染父节点
                        $('#pParentId').val(pData.pParentId + "-" + pData.pParentName)
                        downTreeData = dropdownTreeData(treeData)
                        for (let i = 0; i < downTreeData.length; i++) {
                            if (pData.pParentId === downTreeData[i].id) {
                                downTreeData[i].checked = true;
                            }
                        }
                    } else {
                        layer.msg("数据不存在", {icon: 6});
                    }
                });
            }
            var inst = dropdown.render({
                elem: '#pParentId' //也可绑定到 document，从而重置整个右键
                // ,trigger: 'contextmenu' //contextmenu 右键菜单
                // ,isAllowSpread: false //禁止菜单组展开收缩
                , style: 'width: 235px' //定义宽度，默认自适应
                , id: 'pParentId' //定义唯一索引
                //, data: downTreeData
                , data: [{
                    title: '系统权限根节点'
                    , id: 0
                    , child: downTreeData
                }]
                , click: function (obj) {
                    // 父节点
                    this.elem.val(obj.id+'-'+obj.title);
                    // 父节点字符串 清空
                    $('#pParentIds').val("");
                    parentIdStrs = '0';
                    $('#pParentIds').val(getpIdStr(pAllData, obj.id));
                }
            });
        },
        btn1: function (index, layero) {
            if (!validatePermissionCode()) {

            } else {
                //编辑回调
                layer.close(index);
                var pEditLoadIndex = layer.load(2);
                let permissionForm = $("#permissionForm").serializeObject();
                permissionForm.pParentId = permissionForm.pParentId.split("-")[0];
                $.DPost("/p/v1/saveOrUpdate", permissionForm, headers, function (data) {
                    if (data.code === '00000') {
                        layer.msg("保存成功", {icon: 1, time: 2000}, function () {
                            layer.close(pEditLoadIndex);
                            // 关闭当前页面
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 刷新父页面table(连同查询条件)：
                            // parent.layui.table.reload('userTable');
                            // 表格刷新
                            treeMenuTab.reload('permissionTree', {});
                        });
                    } else {
                        layer.msg("保存失败", {icon: 1, time: 2000}, function () {
                            layer.close(pEditLoadIndex);
                            // 关闭当前页面
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 刷新父页面table(连同查询条件)：
                            // parent.layui.table.reload('userTable');
                            // 表格刷新
                            treeMenuTab.reload('permissionTree', {});
                        });
                    }

                });
            }
        },
        btn2: function (index, layero) {
            //取消回调
        }
    })
}


/**
 * 表单验证
 */
function validatePermissionCode() {
    // 权限名 权限URL 权限规则
    let pName = $('#pName').val();
    let pUrl = $('#pUrl').val();
    let pRule = $('#pRule').val();

    if ($.trim(pName) == '' || $.trim(pName).length <= 0) {
        layer.alert("权限名不能为空", {icon: 5});
        return false;
    }
    if ($.trim(pUrl) == '' || $.trim(pUrl).length <= 0) {
        layer.alert("url不能为空", {icon: 5});
        return false;
    }
    if ($.trim(pRule) == '' || $.trim(pRule).length <= 0) {
        layer.alert("规则不能为空", {icon: 5});
        return false;
    }
    return true;
}

/**
 * 解决下拉树形菜单跳转问题(delete href)
 * @param data
 * @returns {Array}
 */
function dropdownTreeData(data) {
    let dTreeData = []
    for (let i = 0; i < data.length; i++) {
        if (data[i].id != 0) {
            delete data[i].href
            dTreeData.push(data[i])
        }
        if (data[i].children) {
            // 子菜单
            dropdownTreeData(data[i].children)
        } else {
            continue;
        }
    }
    return dTreeData

}

/**
 * 根据节点获取该节点到最终的节点的路径 0/1/2/3
 * @param data 没有递归的权限菜单数据
 * @param id
 * @returns {Array}
 */
function getpIdStr(data, pId) {
    for (let i = 0; i < data.length; i++) {
        if (data[i].pId == pId){
            if (parentIdStrs == undefined){
                parentIdStrs = pId;
            }else{
                parentIdStrs = parentIdStrs + "/" + pId;
            }
            getpIdStr(data, data[i].pParentId)
        }

    }
    return parentIdStrs

}